import Vue from "vue";
import VueRouter from "vue-router";
import WxGateUser from "@/api/WxGateUser";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

const Home = () => import("@/views/Home");
const Login = () => import("@/views/Login");
const Error = () => import("@/views/Error");

Vue.use(VueRouter);

const wxGateUserApi = new WxGateUser();

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home
  },
  {
    path: "/login",
    name: "Login",
    component: Login
  },
  {
    path: "/404",
    component: Error
  },
  {
    path: "*",
    redirect: "/404"
  }
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  //校验登录态
  wxGateUserApi.test(res => {
    if (res.code === 0) {
      if (to.path === "/login") {
        next("/");
      } else {
        next();
      }
    } else {
      if (to.path === "/login") {
        next();
      } else {
        next("/login");
      }
    }
  });
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
